import dayjs from "dayjs";
import { message } from "@/utils/message";
import { ElMessageBox, Sort } from "element-plus";
import { reactive, ref, onMounted, toRaw, computed } from "vue";
import { useUserStoreHook } from "@/store/modules/user";
import { CommonUtils } from "@/utils/common";
import { PaginationProps } from "@pureadmin/table";
import {
  SirSelfCheckQuery,
  getSirSelfCheckListApi,
  exportSirSelfCheckExcelApi,
  deleteSirSelfCheckApi, getProfessionalApi
} from "@/api/airport/dataManage/sirSelfCheck";
import { addInspectionCheckApi } from "@/api/airport/inspection/inspectionCheck";

// 修改 hook 函数，添加 inspectionId 参数
export function useSafetyManageHook(inspectionId?: string) {
  const defaultSort: Sort = {
    prop: "id",
    order: "ascending"
  };

  const pagination: PaginationProps = {
    total: 0,
    pageSize: 8,
    currentPage: 1,
    background: true
  };

  const timeRange = computed<[string, string] | null>({
    get() {
      if (searchFormParams.beginTime && searchFormParams.endTime) {
        return [searchFormParams.beginTime, searchFormParams.endTime];
      } else {
        return null;
      }
    },
    set(v) {
      if (v?.length === 2) {
        searchFormParams.beginTime = v[0];
        searchFormParams.endTime = v[1];
      } else {
        searchFormParams.beginTime = undefined;
        searchFormParams.endTime = undefined;
      }
    }
  });

  const searchFormParams = reactive<SirSelfCheckQuery>({
    professional: "",
    checkContent: ""
  });

  const dataList = ref([]);
  const pageLoading = ref(true);
  const multipleSelection = ref([]);
  const sortState = ref<Sort>(defaultSort);

  // 添加已插入数据的记录
  const insertedData = ref<Set<number>>(new Set());

  // 处理插入操作
  const handleInsert = async (row: any) => {
    if (!inspectionId) {
      message("未获取到检查ID", { type: "warning" });
      return;
    }

    try {
      await addInspectionCheckApi({
        inspectionId: Number(inspectionId),
        selfcheckId: row.id
      });

      // 记录已插入的数据
      insertedData.value.add(row.id);
      message(`已成功插入ID为${row.id}的检查项`, { type: "success" });
    } catch (error) {
      console.error("插入失败:", error);
      message("插入失败", { type: "error" });
    }
  };

  const columns: TableColumnList = [

    { label: "序号", prop: "seq", minWidth: 80 },
    { label: "专业", prop: "professional", minWidth: 120 },
    { label: "检查内容", prop: "checkContent", minWidth: 180, showOverflowTooltip: true },
    { label: "检查标准", prop: "checkStandard", minWidth: 180, showOverflowTooltip: true },
    { label: "符合性判定标准", prop: "complianceCriteria", minWidth: 160, showOverflowTooltip: true },
    { label: "检查方式", prop: "checkMethod", minWidth: 120 },
    { label: "公司依据", prop: "companyBasis", minWidth: 140, showOverflowTooltip: true },
    { label: "法律法规依据", prop: "lawsBasis", minWidth: 160, showOverflowTooltip: true },
    { label: "法律法规条款", prop: "lawsClause", minWidth: 160, showOverflowTooltip: true },
    { label: "融合来源", prop: "integrationSource", minWidth: 140 },
    { label: "检查涉及部门", prop: "checkDepartments", minWidth: 160 },
    {
      label: "操作",
      fixed: "left",
      width: 100,
      cellRenderer: ({ row }) => {
        const isInserted = insertedData.value.has(row.id);
        return (
          <el-button
            size="small"
            type={isInserted ? "default" : "primary"}
            disabled={isInserted}
            onClick={() => handleInsert(row)}
          >
            {isInserted ? "已添加" : "添加"}
          </el-button>
        );
      }
    },
  ];

  // 保留其他函数不变
  function onSortChanged(sort: Sort) {
    sortState.value = sort;
    pagination.currentPage = 1;
    getSirSelfCheckList();
  }

  async function onSearch(tableRef) {
    tableRef.getTableRef().sort("id", "ascending");
    getSirSelfCheckList();
  }

  function resetForm(formEl, tableRef) {
    if (!formEl) return;
    formEl.resetFields();
    searchFormParams.beginTime = undefined;
    searchFormParams.endTime = undefined;
    onSearch(tableRef);
  }

  async function getSirSelfCheckList() {
    pageLoading.value = true;
    CommonUtils.fillSortParams(searchFormParams, sortState.value);
    CommonUtils.fillPaginationParams(searchFormParams, pagination);

    const { data } = await getSirSelfCheckListApi(toRaw(searchFormParams)).finally(() => {
      pageLoading.value = false;
    });

    dataList.value = data.rows;
    pagination.total = data.total;
  }

  async function exportAllExcel() {
    if (sortState.value != null) {
      CommonUtils.fillSortParams(searchFormParams, sortState.value);
    }
    CommonUtils.fillPaginationParams(searchFormParams, pagination);
    CommonUtils.fillTimeRangeParams(searchFormParams, timeRange.value);

    exportSirSelfCheckExcelApi(toRaw(searchFormParams), "自查事项数据.xlsx");
  }

  async function handleDelete(row) {
    await deleteSirSelfCheckApi([row.id]).then(() => {
      message(`您删除了编号为 ${row.id} 的自查事项`, {
        type: "success"
      });
      getSirSelfCheckList();
    });
  }

  async function handleBulkDelete(tableRef) {
    if (multipleSelection.value.length === 0) {
      message("请选择需要删除的数据", { type: "warning" });
      return;
    }

    ElMessageBox.confirm(
      `确认要<strong>删除</strong>编号为<strong style='color:var(--el-color-primary)'>[ ${multipleSelection.value} ]</strong>的自查事项吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        await deleteSirSelfCheckApi(multipleSelection.value).then(() => {
          message(`您删除了编号为 [ ${multipleSelection.value} ] 的自查事项`, {
            type: "success"
          });
          getSirSelfCheckList();
        });
      })
      .catch(() => {
        message("取消删除", { type: "info" });
        tableRef.getTableRef().clearSelection();
      });
  }

  onMounted(getSirSelfCheckList);

  const professionalOptions = ref<string[]>([]);

  // 获取专业列表数据
  const loadProfessionalOptions = async () => {
    try {
      const { data } = await getProfessionalApi();
      professionalOptions.value = data || [];
    } catch (error) {
      // message.error("获取专业列表失败");
      // professionalOptions.value = [];
    }
  };

  // 在组件挂载时加载专业列表
  onMounted(() => {
    loadProfessionalOptions();
  });

  return {
    searchFormParams,
    pageLoading,
    columns,
    dataList,
    pagination,
    defaultSort,
    timeRange,
    multipleSelection,
    onSearch,
    onSortChanged,
    exportAllExcel,
    getSirSelfCheckList,
    resetForm,
    handleDelete,
    handleBulkDelete,
    professionalOptions,
    insertedData // 返回已插入数据记录
  };
};
